<template>
  <basePages>
    <view class="device-add">
      <view class="form-container">
        <view class="form-title">添加设备</view>
        

        <view class="form-item">
          <text class="label">设备类型</text>
          <picker @change="handleTypeChange" :value="typeIndex" :range="deviceTypes">
            <view class="picker">
              {{ deviceTypes[typeIndex] }}
              <uni-icons type="right" size="16" color="#999"></uni-icons>
            </view>
          </picker>
        </view>

        <view class="form-item">
          <text class="label">设备名称</text>
          <input type="text" v-model="formData.metaData.name" placeholder="请输入设备名称" />
        </view>

        <view class="form-item">
          <text class="label">备注信息</text>
          <textarea v-model="formData.metaData.note" placeholder="请输入备注信息（选填）" />
        </view>

        <button class="submit-btn" @click="handleSubmit">添加设备</button>
      </view>
    </view>
  </basePages>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useDeviceStore } from '../../../store/modules/useDeviceStore';
import { useUserStore } from '../../../store/modules/useUserStore';

const deviceStore = useDeviceStore();
const userStore = useUserStore();

const deviceTypes = ['智能手表', '血压计', '血糖仪', '血氧仪', '心电图仪', '体脂秤', '体温计','睡眠监测器','运动监测器', '其他'];
const typeMap = {
  0: 'wearable',
  1: 'BPMonitor',
  2: 'BGMeter',
  3: 'spO2Monitor',
  4: 'ECGMonitor',
  5: 'BFPMonitor',
  6: 'Thermometer',
  7: 'SleepMonitor',
  8: 'ActivityTracker',
  9: 'other'
};
const typeIndex = ref(0);

const formData = reactive({
  deviceType: 'wearable',
  metaData: {
    name: '',
    note: ''
  }
});

// 处理设备类型选择
const handleTypeChange = (e) => {
  typeIndex.value = e.detail.value;
  formData.deviceType = typeMap[e.detail.value];
};

// 提交表单
const handleSubmit = async () => {
  if (!formData.metaData.name) {
    uni.showToast({
      title: '请输入设备名称',
      icon: 'none'
    });
    return;
  }

  let loadingShown = false;
  try {
    // 显示加载中
    uni.showLoading({
      title: '添加中...',
      mask: true
    });
    loadingShown = true;

    // 构造正确的 meta 数据
    const meta = {
      name: formData.metaData.name,
      note: formData.metaData.note || ''
    };
    
    console.log('准备添加设备:', formData.deviceType, meta);
    const result = await deviceStore.addDevice(formData.deviceType, meta);
    console.log('添加设备结果:', result);
    if (result) {
      uni.showToast({
        title: '添加成功',
        icon: 'success'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      throw new Error( '添加失败');
    }
  } catch (error) {
    console.log('添加设备错误:', error);
    
    // 根据错误类型显示不同的提示
    let errorMsg = '添加失败';
    if (error.errMsg === 'request:fail') {
      errorMsg = '网络连接失败，请检查网络设置';
    } else if (error.message) {
      errorMsg = error.message;
    }
    
    uni.showModal({
      title: '提示',
      content: errorMsg,
      showCancel: false
    });
  } finally {
    // 确保在任何情况下都隐藏loading
    if (loadingShown) {
      uni.hideLoading();
    }
  }
};
</script>

<style lang="scss" scoped>
.device-add {
  padding: 20rpx;
  min-height: 100vh;
  background-color: #f8fafc;
}

.form-container {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

  .form-title {
    font-size: 36rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 40rpx;
    text-align: center;
  }
}

.form-item {
  margin-bottom: 30rpx;

  .label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 12rpx;
  }

  input, .picker {
    width: 100%;
    height: 80rpx;
    background: #f5f7fa;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 28rpx;
    color: #333;
  }

  .picker {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  textarea {
    width: 100%;
    height: 160rpx;
    background: #f5f7fa;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    color: #333;
  }
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background: #409EFF;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  margin-top: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &:active {
    opacity: 0.8;
  }
}
</style>
